package com.cgc.shop.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.cgc.shop.model.Product;
import com.cgc.shop.service.ProductService;

@Service("productService")
public class ProductServiceImpl extends BaseServiceImpl<Product> implements ProductService {

	@Override
	public Long getCount(String name) {
		String hql = "select count(*) from Product p where p.name like :name";
		return (Long) getSession().createQuery(hql)
				.setString("name", "%" + name + "%").uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> queryJoinCategory(String name, int pageIndex, int size) {
		String hql = "from Product p left join fetch p.category where p.name like :name";
        return getSession().createQuery(hql)  
                .setString("name", "%" + name + "%")
                .setFirstResult((pageIndex-1) * size)
                .setMaxResults(size)
                .list();
	}

	@Override
	public void deleteByIds(String ids) {
		String hql = "delete Product p where p.id in (" + ids + ")";
		getSession().createQuery(hql).executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> queryByCategoryId(Integer cid) {
		String hql = "from Product p join fetch p.category "
				+ "where p.commend=true and p.open=true and p.category.id=:cid order by p.date desc";
		return getSession().createQuery(hql)
				.setInteger("cid", cid)
				.setFirstResult(0)
				.setMaxResults(4)
				.list();
	}
	
}
